import Vue from 'vue'
import Router from 'vue-router'
import {setTitle} from '@/lib/utils'
import store from '@/store'
import Layout from '@/views/layout/layout.vue'
Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      component: () => import('./views/pages/index.vue'),
      name: 'index',
      meta: { title: 'dashboard', icon: 'dashboard', requireAuth: true },
    },
    {
      path: '/401',
      component: () => import('./views/errorPage/401.vue'),
      name: 'page401',
      meta: { title: 'page401', requireAuth: false },
    },
    {
      path: '/404',
      component: () => import('./views/errorPage/404.vue'),
      name: 'page404',
      meta: { title: 'page404', requireAuth: false },
    },
    {
      path: '/ts',
      component: Layout,
      redirect: '/ts/list',
      children: [{
        path: 'list',
        component: () => import('./views/pages/index.vue'),
        name: 'Home',
        meta: { title: 'dashboard', icon: 'dashboard', requireAuth: true },
      },
      {
        path: 'tab2',
        component: () => import('./views/pages/echart.vue'),
        name: 'Tab2',
        meta: { title: 'tab2', icon: 'tab2', requireAuth: true },
      },
      {
        path: 'classManager',
        component: () => import('./views/pages/classManager.vue'),
        name: 'classManager',
        meta: { title: '班次管理', requireAuth: true },
      }],
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import(/* webpackChunkName: "Login" */'./views/Login/Login.vue'),
      meta: {
        title: '登陆',
        requireAuth: false,
      },
    },
    { path: '*', redirect: '/404' },
  ],
})

router.beforeEach((to, from, next) => {
  if ((to.meta.requireAuth !== undefined && !to.meta.requireAuth) ||
    store.state.userInfo.token || store.state.userInfo.token !== '') {
    console.log('不需要登陆或已登录', to.name)
    next()
  } else {
    console.log('需要登陆', to.name)
    next('/login')
  }
})

router.afterEach((to, from) => {
  setTitle(to.meta.title)
})

export default router
